from django.utils.decorators import method_decorator

from gis.admin.decorators import require_login, check_permission
from gis.common.django_ext.decorators import validate_parameters
from gis.common.django_ext.views import BaseView, PaginationResponse
from itpay.core.agency import receipt_service
from itpay.server_admin.view.agency.helper import wrapper_receipt_address
from . import receipt_form


class ReceiptConfView(BaseView):
    @method_decorator(require_login)
    @method_decorator(check_permission('receipt_conf_get'))
    def get(self, request):
        return dict(conf=receipt_service.get_all_receipt_conf())


class ReceiptConfDetailView(BaseView):
    @method_decorator(require_login)
    @method_decorator(check_permission('receipt_conf_get'))
    def get(self, request, conf_id):
        receipt_service.get_receipt_conf_by_id(conf_id)

    @method_decorator(require_login)
    @method_decorator(check_permission('receipt_conf_update'))
    @method_decorator(validate_parameters(receipt_form.UpdateReceiptConfSchema))
    def put(self, request, conf_id, cleaned_data):
        receipt_service.update_receipt_conf(conf_id, **cleaned_data)
        return dict(id=conf_id)


class ReceiptAddressListView(BaseView):
    @method_decorator(require_login)
    @method_decorator(check_permission('receipt_addresses_get'))
    @method_decorator(validate_parameters(receipt_form.QueryReceiptAddressSchema))
    def get(self, request, cleaned_data):
        c, ls = receipt_service.list_receipt_addresses(**cleaned_data)
        return PaginationResponse(c, [wrapper_receipt_address(e, True, True, True) for e in ls])


class ReceiptAddressDetailView(BaseView):
    @method_decorator(require_login)
    @method_decorator(check_permission('receipt_addresses_get'))
    def get(self, request, receipt_id):
        return receipt_service.get_receipt_address(receipt_id)

    @method_decorator(require_login)
    @method_decorator(check_permission('receipt_addresses_del'))
    def delete(self, request, receipt_id):
        receipt_service.delete_receipt_address(receipt_id)
        return dict(id=receipt_id)

    @method_decorator(require_login)
    @method_decorator(check_permission('receipt_addresses_update'))
    @method_decorator(validate_parameters(receipt_form.UpdateReceiptAddressSchema))
    def put(self, request, receipt_id, cleaned_data):
        receipt_service.update_receipt_part_field(receipt_id, **cleaned_data)


class ReceiptAddressStatusView(BaseView):
    @method_decorator(require_login)
    @method_decorator(check_permission('receipt_addresses_status'))
    @method_decorator(validate_parameters(receipt_form.UpdateReceiptAddressStatusSchema))
    def put(self, request, receipt_id, cleaned_data):
        receipt_service.update_receipt_address_status(receipt_id, **cleaned_data)
